<template>
  <div>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="130px"
      class="demo-ruleForm"
      size="mini"
    >
      <el-row>
        <el-col :span="11">
          <el-form-item label="机构" prop="deptId">
            <el-select
              v-model="ruleForm.deptId"
              :disabled="ifSchoolId"
              @change="gradeList(ruleForm.deptId)"
              placeholder="请选择机构"
              clearable
            >
              <el-option
                :label="item.name"
                :value="item.id"
                v-for="(item,index) in schoolList"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请输入姓名" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="11">
          <el-form-item label="年级" prop="glassId">
            <el-select
              clearable
              v-model="ruleForm.glassId"
              @change="classList(ruleForm.glassId)"
              placeholder="请选择年级"
              size="mini"
            >
              <el-option
                :label="item.name"
                :value="item.id"
                v-for="(item,index) in gradeData"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="班级" prop="classId">
            <el-select clearable v-model="ruleForm.classId" placeholder="请选择班级" size="mini">
              <el-option
                :label="item.name"
                :value="item.id"
                v-for="(item,index) in classData"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="11">
          <el-form-item label="学号">
            <el-input v-model="ruleForm.studentNumber" placeholder="请输入学号" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证号" prop="IDNmber">
            <el-input v-model="ruleForm.IDNmber" placeholder="请输入身份证号" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="ruleForm.sex">
              <el-radio label="男" value="0"></el-radio>
              <el-radio label="女" value="1"></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="民族">
            <el-select filterable v-model="ruleForm.ethnic" placeholder="请选择民族" clearable>
              <el-option
                :label="item"
                :value="item"
                v-for="(item,index) in ethnicList"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="11">
          <el-form-item label="联系电话" prop="familyPhone">
            <el-input v-model="ruleForm.familyPhone" placeholder="请输入联系电话" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="籍贯">
            <el-input v-model="ruleForm.nativePlace" placeholder="请输入籍贯" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="11">
          <el-form-item label="家庭住址">
            <el-input v-model="ruleForm.familyAddress" placeholder="请输入家庭住址" clearable></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="是否住校" prop="ifInSchool">
            <el-select v-model="ruleForm.ifInSchool" placeholder="请选择是否住校" clearable>
              <el-option label="住校" value="1"></el-option>
              <el-option label="走读" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item label="状态" prop="status">
            <el-select v-model="ruleForm.status" placeholder="请选择状态" clearable>
              <el-option label="在校" value="1"></el-option>
              <el-option label="毕业" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item>
        <el-button @click="resetForm('ruleForm')">{{$t("action.reset")}}</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">{{$t("action.save")}}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import Cookies from "js-cookie";
import ethnic from "@/assets/json/ethnic.js";
import { format } from "@/utils/datetime";

export default {
  name: "edit",
  props: {
    msg: ""
  },
  data() {
    return {
      url: this.$Config.url,
      ethnicList: [], //名族列表
      schoolList: [], //机构列表
      gradeData: [], //年级列表
      classData: [], //班级列表
      id: "", //修改对应的id
      ifSchoolId: false,
      ruleForm: {
        name: "", //姓名
        studentNumber: "", //学号
        IDNmber: "", //身份证号
        sex: "", //性别
        ethnic: "", //名族
        deptId: "", //机构id
        glassId: "", //年级id
        classId: "", //班级id

        school: "", //学校
        grade: "", //年级
        classBan: "", //班级
        inSchoolDate: "", //入学时间
        outSchoolDate: "", //毕业时间
        cardType: "", //卡类型

        familyPhone: "", //联系电话
        emergencyContact: "", //紧急联系人
        emergencyContactPhone: "", //紧急联系人电话
        emergencyContactRelation: "", //紧急联系人关系
        nativePlace: "", //籍贯
        familyAddress: "", //家庭住址
        ifInSchool: "", //是否住校
        status: "" //状态
      },
      rules: {
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" }
        ],
        // studentNumber: [
        //   { required: true, message: "请输入学号", trigger: "blur" },
        //   { max: 20, message: "长度不能超过20个字符", trigger: "blur" }
        // ],
        IDNmber: [
          { required: true, message: "请输入身份证号", trigger: "blur" },
          {
            pattern: /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/,
            message: "证件号码格式有误！",
            trigger: "blur"
          }
        ],
        glassId: [{ required: true, message: "请选择年级", trigger: "change" }],
        classId: [{ required: true, message: "请选择班级", trigger: "change" }],
        deptId: [{ required: true, message: "请选择机构", trigger: "change" }],

        sex: [{ required: true, message: "请选择性别", trigger: "change" }],
        // ethnic: [{ required: true, message: "请选择名族", trigger: "change" }],
        school: [{ required: true, message: "请选择学校", trigger: "change" }],

        inSchoolDate: [
          { required: true, message: "请选择入学时间", trigger: "change" }
        ],
        outSchoolDate: [
          { required: true, message: "请选择毕业时间", trigger: "change" }
        ],
        familyPhone: [
          { required: true, message: "请输入联系电话", trigger: "blur" }
        ],
        // emergencyContact: [
        //   { required: true, message: "请输入监护人", trigger: "blur" }
        // ],
        // emergencyContactRelation: [
        //   { required: true, message: "请选择与监护人关系", trigger: "change" }
        // ],
        // nativePlace: [
        //   { required: true, message: "请输入籍贯", trigger: "blur" }
        // ],
        // familyAddress: [
        //   { required: true, message: "请输入家庭住址", trigger: "blur" }
        // ],
        ifInSchool: [
          { required: true, message: "请选择是否住校", trigger: "change" }
        ],
        status: [{ required: true, message: "请选择状态", trigger: "change" }]
      },
      formData: {}
    };
  },
  mounted() {
    this.ethnicList = ethnic;
    this.getSchool();
    this.schoolId();
  },
  methods: {
    classList(id) {
      const that = this;
      this.$axios
        .get(that.url + "/admin/class/list", {
          params: {
            gradeId: id
          },
          headers: {
            "x-baie-admin-token": Cookies.get("token")
          }
        })
        .then(function(res) {
          if (res.data.code == 200) {
            that.classData = res.data.data;
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    gradeList(id) {
      const that = this;
      this.$axios
        .get(that.url + "/admin/grade/list", {
          params: {
            deptId: id
          },
          headers: {
            "x-baie-admin-token": Cookies.get("token")
          }
        })
        .then(function(res) {
          if (res.data.code == 200) {
            that.gradeData = res.data.data;
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    schoolId() {
      try {
        const deptId = JSON.parse(localStorage.getItem("userInfo")).deptId;
        if (deptId == null || deptId == "") {
          this.ifSchoolId = false;
          this.ruleForm.deptId='';
        } else {
          this.ifSchoolId = true;//不能点击
          this.gradeList(deptId);
        }

        this.ruleForm.deptId = deptId;
      } catch (error) {}
    },
    getSchool() {
      const that = this;
      this.$axios
        .get(that.url + "/admin/dept/list", {
          headers: {
            "x-baie-admin-token": Cookies.get("token")
          }
        })
        .then(function(res) {
          if (res.data.code == 200) {
            that.schoolList = res.data.data;
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    resetData(id = 1) {
      this.$refs["ruleForm"].resetFields();//先清空
      const that = this;
      const deptId = JSON.parse(localStorage.getItem("userInfo")).deptId;
      this.schoolId();

      if (id) {
        this.id = id;
      }
      this.$axios
        .get(that.url + "/admin/student/get/{id}", {
          params: {
            id
          },
          headers: {
            "x-baie-admin-token": Cookies.get("token")
          }
        })
        .then(function(res) {
          if (res.status == 200) {
            let data = res.data.data;
            that.ruleForm = {
              name: data.name, //姓名
              studentNumber: data.studentNo, //学号
              IDNmber: data.idNo, //身份证号
              sex: data.gender, //性别
              ethnic: data.nation, //名族
              inSchoolDate: data.entranceTime, //入学时间
              outSchoolDate: data.graduateTime, //毕业时间
              deptId:data.deptId,
              classId:data.classId,//班级id
              glassId:data.gradeId,//年级id
              familyPhone: data.phone, //联系电话
              emergencyContact: data.guardian, //紧急联系人
              emergencyContactRelation: data.guardianRela, //紧急联系人关系
              nativePlace: data.nativePlace, //籍贯
              familyAddress: data.address, //家庭住址
              ifInSchool: data.dormitoryFlg == 1 ? "住校" : "走读", //是否住校
              status: data.status.toString() //状态
            };
            that.id = data.id;
            that.gradeList(data.deptId);
            that.classList(data.gradeId);

          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    submitForm(formName) {
      const that = this;
      this.$refs[formName].validate(valid => {
        if (valid) {
          that.send();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    send() {
      const that = this;
      const data = {
        id: this.id,
        address: that.ruleForm.familyAddress, //地址
        classId: 1, //班级id
        dormitoryFlg: that.ruleForm.ifInSchool == 0 ? true : false, //是否住校
        entranceTime: format(this.ruleForm.inSchoolDate), //入学时间
        gender: that.ruleForm.sex, //性别
        graduateTime: format(this.ruleForm.outSchoolDate), //毕业时间
        guardian: that.ruleForm.emergencyContact, //监护人
        guardianRela: that.ruleForm.emergencyContactRelation, //监护人关系
        idNo: that.ruleForm.IDNmber, //身份证号码
        name: that.ruleForm.name, //学生姓名
        nation: that.ruleForm.ethnic, //名族
        nativePlace: that.ruleForm.nativePlace, //籍贯
        phone: that.ruleForm.familyPhone, //联系电话
        status: that.ruleForm.status, //状态
        studentNo: that.ruleForm.studentNumber, //学号
        deptId: that.ruleForm.deptId, //机构id
        gradeId:that.ruleForm.gradeId,//年级id
        classId:that.ruleForm.classId,//班级id
      };
      this.$axios
        .post(
          that.url + "/admin/student/saveOrUpdate",
          that.$qs.stringify(data),
          {
            headers: {
              "x-baie-admin-token": Cookies.get("token")
            }
          }
        )
        .then(function(res) {
          if (res.status == 200) {
            if(res.data.code==200){
              if (that.msg == 1) {
                that.$message({
                  message: "添加成功",
                  type: "success"
                });
              } else {
                that.$message({
                  message:"修改成功",
                  type: "success"
                });
              }
              that.$emit("hideEdit", false);
            }else{
              that.$message({
                message: res.data.msg,
                type: "warning"
              });
            }
          } else {
            that.$message({
              message: res.statusText,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.id="";
      this.schoolId();
    }
  }
};
</script>

<style scoped lang="scss">
.el-select,
.el-date-editor {
  width: 100%;
}
</style>
